package com.ahy231.controller;

import com.ahy231.dto.Result;
import com.ahy231.dto.ResultCode;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class ExceptionController {


    /**
     * 捕捉shiro的异常
     */
    @ExceptionHandler(ShiroException.class)
    public Result handle401() {
        Result result = new Result(ResultCode.REFUSE_REQUEST);
        result.setData("权限不足");
        return result;
    }

    /**
     * 捕捉其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public Result globalException(HttpServletRequest request, Throwable ex) {
        Result result = new Result();
        result.setCode(getStatus(request).value());
        result.setMessage("访问失败");
        result.setData(ex.getMessage());
        return result;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
